package org.example.handler;

import lombok.extern.slf4j.Slf4j;
import org.example.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.AccessDeniedException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 处理权限异常
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public ResponseEntity<Result> handleAccessDenied(AccessDeniedException e) {
        log.info("处理权限异常{}",e.getMessage());
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Result.error(e.getMessage()));
    }

    /**
     * 处理sql异常
     * @param ex
     * @return
     */
    //处理一些数据库查询返回问题
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity<Result> handleIllegalArgumentException(IllegalArgumentException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Result.error(ex.getMessage()));
    }

    //处理事务异常
    @ExceptionHandler(TransactionSystemException.class)
    @ResponseBody
    public ResponseEntity<Result> handleTransactionException(TransactionSystemException ex) {
        // 捕获事务异常并返回错误信息
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.error("事务异常: " + ex.getRootCause().getMessage()));
    }


    //处理其他异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Result> handleException(Exception ex) {
        Throwable cause = ex.getCause();
        log.info("处理异常{}",ex.getMessage());
        if (cause instanceof AccessDeniedException) {
            log.info("处理权限异常{}",ex.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(Result.error("权限不足：" + cause.getMessage()));
        }
        log.info("处理其他异常{}",ex.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.error("An unexpected error occurred: " + cause.getMessage()));
    }

}